import React,{Component,PropTypes} from 'react';
import Tags from './../Tags';
import {redirect,backward} from 'lib/utils';
import API, {} from 'lib/api';

import {Form, Select,Table,Button, InputNumber} from 'antd';
import './style.less';

const FormItem = Form.Item;
const Option = Select.Option;
const { Column, ColumnGroup } = Table;

class Standard extends Component{
    constructor(props){
        super(props);

        this.state={
            hasImg:true ,       // 有图片
            standard:[],        // 产品规格
            tableItem:[],       // 表格项

            tableData:[],       // 表格数据
            checkedStandard:[]

        }
    };

    componentWillMount(){

        //API.fetch("",{id:id},resp=>{
            /* ====== 共同的数据 ======
                需要请求的数据
                1. standard==>产品规格
                2. 商品类型数据

            */
            const standard = [
                {id:1,name:"颜色", data:["白色","黑色","蓝色"]},
                {id:2,name:"尺寸", data:["电容屏","蓝宝石","电容"]},
                {id:3,name:"按钮", data:["方形","圆形","虚拟"]},
                {id:4,name:"材质", data:["pv","玻璃","钻石"]},
            ];

            const select = [
                {option:"手机",value:"phone"},
                {option:"电脑",value:"computer"}
            ];


            this.setState({ standard:standard,select:select});
        //}
    };

    componentDidMount(){
        /* ====== 商品编辑 ======
        *
        * 需要请求的数据
        * 1 types ==> 商品类型
        * 2 tableData ==> 表格数据
        *   格式二维数组:
        *   [
        *         黑色  蓝宝石    价格      库存
        *       [ [1,1],[2,1],{price:10,inventory:5} ]
        *   ]
        *
        * */

        if(this.props.id){
            //API.fetch("",{id:id},resp=>{    请求需要编辑的数据 FormData

                // 需要替换的地方
                const FormData = {
                    types:"phone",
                };

                const tableData=[
                    [[1,1],[2,1],{inventory:5,price:10}],
                    [[1,1],[2,2],{inventory:6,price:11}],
                    [[1,2],[2,1],{inventory:7,price:12}],
                    [[1,2],[2,2],{inventory:8,price:13}],
                ];
                // 需要替换的地方



                let mapData=[];
                tableData.map(v=>{
                    let temp=[];
                    v.map(item=>{
                        if(item instanceof Array){ temp.push(item) }
                    });
                    mapData.push(temp);
                });

                this.setState({mapData:mapData});
                this.edit_data(tableData,this.state.standard,FormData);
                this.props.form.setFieldsValue(FormData);
             //};
        }
    };

    /* ===================
    *       编辑状态
    *  ===================*/
    // 编辑状态数据处理
    edit_data=(tableData,standard,FormData)=>{
        let default_tags=[], tableTitle=[], tableList=[];
        let temp_tags=[], temp_title=[];

        tableData.map(item=>{
            let temp_list = [];
            item.map(v=>{
                if(v.constructor==Array){
                    temp_tags.push(standard[v[0]-1].data[v[1]]);  // 默认标签
                    temp_title.push(standard[v[0]-1].name);       // 默认标题
                    temp_list.push(standard[v[0]-1].data[v[1]]);  // 默认表格列表
                };
            });
            temp_list= [...temp_list,...["",""]];
            tableList.push(temp_list);
        });

        default_tags = Array.from(new Set(temp_tags));

        temp_title = [...temp_title,...["价格","库存"]];
        tableTitle = Array.from(new Set(temp_title));


        this.set_checkedStandard(default_tags,standard);


        this.setState({
            default_tags:default_tags,
            tableTitle:tableTitle,
            tableData:tableList
        },_=>{
            let initData=this.props.form.getFieldsValue();
            let final = this.get_initData(initData,tableData);

            this.props.form.setFieldsValue(final);
        })
    };
    //设置初始选中的标签
    set_checkedStandard=(default_tags,standard)=>{

        let temp1=[];
        standard.map(item=>{
            item.data.map((v,k)=>{
                default_tags.map(tag=>{
                    if(v==tag){
                        let obj = {id:item.id,identify:[item.id,k],tag:tag};
                        temp1.push(obj)
                    }
                })
            })
        });


        let temp_ids = [],ids=[];
        temp1.map(v=>{ temp_ids.push(v.id) });

        ids=Array.from(new Set(temp_ids))

        let temp2=[];
        ids.map(v=>{
            let temp3=[];
            temp1.map(v1=>{
                if(v==v1.id){
                    temp3.push(v1)
                }
            });
            temp2.push(temp3)
        });

        this.setState({ checkedStandard:temp2});
    };

    get_initData=(initData,tableData)=>{
        let temp_tableData=JSON.stringify( tableData );  // 转JSON深拷贝
        let copy_tableData=JSON.parse( temp_tableData );

        // 默认数据
        let temp1=[];
        copy_tableData.map((item,key)=>{
            let temp2=[];
            item.map(v=>{
                if(!(v instanceof Array)){
                    temp2.push(v)
                }
            });
            temp1.push(temp2);
        });

        // formData

        let formData = Object.keys(initData);
        let temp_formData = [];

        formData.map(v=>{
            if(v!="types"){
                temp_formData.push(v.split(","))
            }
        });

        let temp2_formData = [];
        for(let i=0; i<temp_formData.length/2; i++){
            let temp3 =[];
            temp_formData.map(v=>{
                v[0]==i?temp3.push(v):null
            });
            temp2_formData.push(temp3);
        };

        let temp3_formData=[]
        for(let i=0; i<temp2_formData.length; i++){
            let obj = {};

            obj[temp2_formData[i][0].join(",")]=temp1[i][0].price;
            obj[temp2_formData[i][1].join(",")]=temp1[i][0].inventory;

            temp3_formData.push(obj);
        };

        let final={};
        temp3_formData.map(v=>{ final={...final,...v} });
        return final
    }


    // 已选择的规格集合
    getStandard=(id,temp)=>{
        let {checkedStandard} = this.state;
        // console.log(checkedStandard)

        let state = false,idx;

        if(checkedStandard.length>0){
            checkedStandard.map((v,k)=>{
                if(v[0].id == id){ idx=k; state=true }
            });

            state ? checkedStandard[idx] = temp : checkedStandard.push(temp);

        }else {
            checkedStandard.push(temp);
        };

        let newStandard = this.sortedCollections(checkedStandard);
        let tableTitle = this.getTableTitle(newStandard);

        this.descartes(newStandard);


        this.setState({
            tableTitle:tableTitle,
            checkedStandard:newStandard
        });

    };


    // 对规格集合进行排序
    sortedCollections = (checkedStandard) =>{
        const {standard} = this.state;
        let sequence_id =[],tempStandard=[],newStandard=[] ;
        standard.map(v=>{ sequence_id.push(v.id) });

        sequence_id.map(v=>{
            checkedStandard.map(v1=>{
                if(v1.length>0){
                    v1[0].id == v ? tempStandard.push(v1) : null;
                }
            });
        });

        // 对具体规格属性再排序
        tempStandard.map(v=>{
            let data ;
            if(v.length>1){
                data = this.getData(v[0].id);
                let temp=[] ;
                data.map(v2=>{
                    v.map(v3=>{
                        if(v3.tag==v2){
                            temp.push(v3)
                        }
                    })
                });

                v=temp;
                newStandard.push(v)

            }else { newStandard.push(v) };

        });
        return newStandard;
    };


    // 根据id获取规格的数据
    getData=(id)=>{
        let data;
        const {standard} = this.state;
        standard.map(v=>{ v.id==id? data = v.data :null });
        return data;
    };


    // 获取表格头
    getTableTitle=(newStandard)=>{
        const {standard} = this.state;
        let tableTitle = [];

        newStandard.map(v=>{
            standard.map(v1=>{
                v[0].id == v1.id ? tableTitle.push(v1.name) : null;
            });
        });

        tableTitle = [...tableTitle,...["价格","库存"]];
        if(newStandard.length==0){tableTitle = []}
        return tableTitle;
    };


    /**  笛卡尔集  **/
    descartes = (standard) =>{
        if(standard.length==0){
            this.setState({tableData:[], mapData:[]});


        }else if(standard.length==1){
            const {tableData,mapData} = this.single_data(standard);
            this.setState({tableData:tableData,mapData:mapData});


        }else {
            this.setState({combineData:[]});

            for(let i=0; i<standard.length; i++){
                if(i+1<standard.length){
                    if(i==0){
                        let {mapData,tableData,combineData} =this.arr_combine(standard[i],standard[i+1]);
                        this.setState({mapData:mapData, tableData:tableData, combineData:combineData});

                    }else{
                        setTimeout(_=>{
                            this.multipleData(this.state.combineData,standard[i+1])
                        },10)

                    }
                }
            }
        }
    };

    //只有一组数据规格的情况
    single_data = (data)=>{
        let tableData = [];
        let mapData = [];

        data.map(v=>{
            v.map(v1=>{
                let temp = [...[v1.tag],...["",""]];
                tableData.push(temp);

                let temp2 = [v1.identify];
                mapData.push(temp2)
            })
        });

        return {tableData,mapData};
    };

    // 两组以上数据处理
    multipleData = (combine,data) =>{
        let mapData=[],tableData = [], combineData=[];

        for(let i=0; i<data.length; i++){
            for(let j=0; j<combine.length; j++){
                // 组合数据
                combineData.push([...combine[j],...[data[i]]]);
            }
        };

        // 映射数据 / table数据
        combineData.map(v=>{
            let temp = [];
            let temp2 = [];
            v.map(v1=>{
                temp.push(v1.identify);

                temp2.push(v1.tag);
            });

            mapData.push(temp);
            tableData.push([...temp2,...["",""]]);
        });

        // tableData表格渲染数据 mapData表格映射数据(用于提交)   combineData所有数据
        this.setState({mapData:mapData, tableData:tableData, combineData:combineData});
    };

    // 两组数据合并
    arr_combine = (arr1,arr2) =>{
        // console.log(combine,data2);
        let mapData=[],tableData = [],combineData = [];

        for(let i=0; i<arr1.length; i++){
            for(let j=0; j<arr2.length; j++){
                // table数据
                let temp1 = [...[arr1[i].tag,arr2[j].tag],...["",""]]
                tableData.push(temp1);

                // 与table互相映射数据
                let temp2 = [arr1[i].identify,arr2[j].identify];
                mapData.push(temp2);

                // 组合数据
                let temp3 = [ arr1[i],arr2[j] ];
                combineData.push(temp3);
            }
        };

        return {mapData,tableData,combineData}
    };

    /**  表单数据处理  **/
    filterFormData = (values) =>{

        /*   step1  选出列表数据  */
        let step1_data=[];
        for(let i in values){
            if(i!="types"){  step1_data.push(i.split(",")) }
        };

        if(step1_data.length>0){
            /*   step2  数据排序  */
            let step2_data=[];
            for(let i=0; i<step1_data.length/2; i++){
                let temp=[];
                step1_data.map(v=>{
                    v[0]==i? temp.push(v[0]+","+v[1]) :null
                });

                step2_data.push(temp)
            };


            /*   step3  数据转换 索引==>价格和库存  */
            let step3_data=[];
            for(let i=0; i<step2_data.length; i++){
                let obj = {
                    price:values[step2_data[i][0]],
                    inventory:values[step2_data[i][1]]
                };

                step3_data.push(obj);
            };


            /*   step4  数据合并  */
            const {mapData}=this.state;
            let temp_arr=JSON.stringify( mapData );  // 转JSON深拷贝
            let step4_data=JSON.parse( temp_arr );

            step4_data.map((v,k)=>{
                v.push(step3_data[k])
            });

            return step4_data;
        }


    }


    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                let FormData = this.filterFormData(values);  // FormData 表格所有规格的最终数据

                let goods_types = values.types;              // 商品类型 表格所有规格的最终数据

                console.log(FormData,goods_types)
            }
        });
    }


    render(){
        const { getFieldDecorator } = this.props.form;
        const { tableTitle,tableData,standard } = this.state;

        return(
            <Form onSubmit={this.handleSubmit} className="standard-info">

                <FormItem label="商品类型" labelCol={{ span: 4 }} wrapperCol={{ span: 8 }} >
                    {getFieldDecorator('types', {
                        rules: [{ required: true, message: '请选择商品类型' }],
                    })(
                        <Select placeholder="请选择商品类型" onChange={this.handleSelectChange}
                        >{
                            this.state.select?
                                this.state.select.map((v,k)=>(
                                    <Option key={k} value={v.value}>{v.option}</Option>
                                ))
                                :null
                        }
                        </Select>
                    )}
                </FormItem>


                {/*   产品规格   */}
                <FormItem label="产品规格" labelCol={{ span: 4 }}  wrapperCol={{ span: 8 }} >
                    <div>
                        {
                            standard.map((item,idx)=>(
                                <Tags id={item.id} key={idx} title={item.name} tagsFromServer={item.data}
                                      handleClick = {this.renderTable} default_tags={this.state.default_tags}
                                      getStandard={this.getStandard} Pid={this.props.id}
                                />
                            ))
                        }
                    </div>
                </FormItem>


                <div className="ant-row ant-form-item">
                    <div className="ant-col-2 ant-form-item-label"></div>
                    <div className="standard-table ant-col-16 ant-form-item-control-wrapper">
                        {
                            (tableTitle&&tableTitle.length)>0?
                                <div className="standard-table_title">
                                    {
                                        tableTitle.map((v,k)=>( <span key={k} className="column">{v}</span> ))
                                    }
                                </div>
                                :null
                        }

                        <div className="standard-table_body">
                            {
                                tableData?
                                    tableData.map((v,k)=>(
                                        <div className="items" key={k}>
                                            {
                                                v.map((item,idx)=>(
                                                    idx<v.length-2?
                                                        <span className="column" key={idx}>{item}</span>
                                                        :idx==v.length-2?
                                                        <FormItem key={idx} className="column">
                                                            {getFieldDecorator(`${k+','+idx}`, {
                                                                rules: [{ required: true, message: ' ' }],
                                                            })(
                                                                <InputNumber precision={2} min={0}/>
                                                            )}
                                                        </FormItem>
                                                        :   <FormItem key={idx} className="column">
                                                            {getFieldDecorator(`${k+','+idx}`, {
                                                                rules: [{ required: true, message: ' ' }],
                                                            })(
                                                                <InputNumber precision={0} min={0}/>
                                                            )}
                                                        </FormItem>
                                                ))
                                            }

                                        </div>
                                    ))
                                    :null
                            }

                        </div>
                    </div>
                </div>

                <FormItem wrapperCol={{span:8,offset:4}} >
                    <Button type="primary" htmlType="submit">保存</Button>
                </FormItem>
            </Form>
        )
    }
};

export default Form.create()(Standard);